package com.studyroom.component;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import com.studyroom.dto.UserDTO;
import com.studyroom.entity.User;
import com.studyroom.service.UserService;
import com.studyroom.utils.UserHolder;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //自定义授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //自定义登录认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取用户认证信息
        String principal=authenticationToken.getPrincipal ().toString ();
        //2.调用业务层获取用户信息(数据库)
            User user = userService.login (principal);
        //3.非空判断,将数据封装返回
        if(user!=null){
            AuthenticationInfo info=new SimpleAuthenticationInfo (
                    principal,
                    user.getPassword (),
                    ByteSource.Util.bytes ("DarkKnight"),
                    authenticationToken.getPrincipal ().toString ()
            );
            UserDTO userDTO= BeanUtil.copyProperties (user,UserDTO.class);
            UserHolder.saveUser (userDTO);
            return info;
        }
        return null;
    }
}
